﻿using Common.Identity;
using Common.ResultFormat;
using Gateway.Identity;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer4;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Gateway.Controllers
{
    /// <summary>
    /// 登录接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly ResourceOwnerPasswordValidator _resourceOwnerPasswordValidator;
        private readonly RestClient restClient = new RestClient();
        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="resourceOwnerPasswordValidator"></param>
        public LoginController(ILogger<LoginController> logger, IResourceOwnerPasswordValidator resourceOwnerPasswordValidator)
        {
            _logger = logger;
            _resourceOwnerPasswordValidator = resourceOwnerPasswordValidator as ResourceOwnerPasswordValidator;
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="user">user</param>
        /// <returns></returns>
        [HttpPost]
        public Result<TokenResult> LoginIn(LoginModelDto user)
        {
            try
            {
                if (user== null || string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.PassWord))
                {
                    return Result<TokenResult>.Error("用户名密码不能为空");
                }
                string username = this.User.Identity.Name;
                _logger.LogInformation(username);
                string ipv4 = this.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                string ipv6 = this.HttpContext.Connection.RemoteIpAddress.MapToIPv6().ToString();

                restClient.BaseUrl = new Uri((this.HttpContext.Request.IsHttps?"https":"http")+"://"+this.HttpContext.Request.Host.Value);
                RestRequest request = new RestRequest("/connect/token");
                request.AddParameter("client_id", OAuthClientConfig.ClientId);
                request.AddParameter("client_secret", OAuthClientConfig.Secret);
                request.AddParameter("grant_type", OAuthClientConfig.GrantType);
                request.AddParameter("username", user.UserName);
                request.AddParameter("password", user.PassWord);
                request.AddParameter("scope", OAuthClientConfig.ApiName);
                var response = restClient.ExecuteAsPost(request, "post");
                if (string.IsNullOrEmpty(response.Content))
                {
                    return Result<TokenResult>.Error(response.StatusDescription);
                }
                Dictionary<string, string> tokenInfo = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content);
                if (tokenInfo.ContainsKey("IsError") && tokenInfo["IsError"] == "True")
                {
                    return Result<TokenResult>.Error(tokenInfo["Error"]);
                }
                else
                if (tokenInfo.ContainsKey("error"))
                {
                    return Result<TokenResult>.Error(tokenInfo["error"]);
                }
                return Result<TokenResult>.Success(new TokenResult() { AccessToken = "Bearer " + tokenInfo["access_token"], ExpiresIn = OAuthServerConfig.ExpireIn});
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return Result<TokenResult>.Error(ex.Message);
            }
        }


        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Result LoginOut() 
        {
            try
            {
                HttpContext.SignOutAsync();
                return Result.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return Result.Error(ex.Message);
            }
        }
    }
}
